package com.decelo.jpa.result;

import com.google.gson.internal.LinkedTreeMap;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;

public class PageResult<T>  {
    /** 页码 */
    protected int pageNo = 1;
    /** 每页数据 */
    protected int pageSize = 20;

    /** 返回结果 */
    protected List<T> result = Collections.emptyList();

    /** 数据总数 */
    protected long totalCount = -1;


    /**
     * 获得当前页的页号,序号从1开始,默认为1.
     */
    public int getPageNo() {
        return pageNo;
    }

    /**
     * 设置当前页的页号,序号从1开始,低于1时自动调整为1.
     */
    public void setPageNo(final int pageNo) {
        this.pageNo = pageNo;

        if (pageNo < 1) {
            this.pageNo = 1;
        }
    }

    public PageResult<T> pageNo(final int thePageNo) {
        setPageNo(thePageNo);
        return this;
    }

    /**
     * 获得每页的记录数量
     */
    public int getPageSize() {
        return pageSize;
    }

    /**
     * 设置每页的记录数量,低于1时一页显示全部记录.
     */
    public void setPageSize(final int pageSize) {
        this.pageSize = pageSize;
    }

    public PageResult<T> pageSize(final int thePageSize) {
        setPageSize(thePageSize);
        return this;
    }

    public List<T> getResult() {
        return result;
    }

    public void setResult(List<T> result) {
        this.result = result;
    }

    public PageResult<T> result(List<T> result) {
        setResult(result);
        return this;
    }

    public long getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(long totalCount) {
        this.totalCount = totalCount;
    }

    public PageResult<T> totalCount(long totalCount) {
        setTotalCount(totalCount);
        return this;
    }

    /**
     * 根据pageNo和pageSize计算当前页第一条记录在总结果集中的位置,序号从1开始.
     */
    public int getFirst() {
        return (this.totalCount == 0) ? 0 : ((pageNo - 1) * pageSize) + 1;
    }


    public long getTotalPages() {
        if (totalCount < 0)
            return 0;

        long count = totalCount / pageSize;
        if (totalCount % pageSize > 0) {
            count++;
        }
        return count;
    }


}
